package net.lc7.curator;

import net.lc7.util.ZkPropertiesUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;

/**
 * @Description: Curator对zk进行基本操作，Curator采用流式风格API
 * @Author: Jason.zhu
 * @Create: 2019/05/24 17:55
 */

public class CuratorClient {
    private static CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(
            ZkPropertiesUtil.getZkServerIp(),
            new RetryNTimes(10, 5000));

    private static String path = "/curator_node";

    public static void main(String[] args) throws Exception {

        curatorFramework.start();

        //create node
        String data = "curator_data";
        curatorFramework.create().creatingParentsIfNeeded().forPath(path,data.getBytes());


        //get Node and Data
        print("ls", "/");
        print(curatorFramework.getChildren().forPath("/"));

        print("get", path);
        print(curatorFramework.getData().forPath(path));

        //update node data

        String dataNew = "curator_data_new";
        print("set", path, dataNew);
        curatorFramework.setData().forPath(path, dataNew.getBytes());

        print("get", path);
        print(curatorFramework.getData().forPath(path));

        //remove node
        print("delete", path);
        curatorFramework.delete().forPath(path);
        print("ls", "/");
        print(curatorFramework.getChildren().forPath("/"));

        curatorFramework.close();
    }

    private static void print(String... cmds) {
        StringBuilder text = new StringBuilder("$ ");
        for (String cmd : cmds) {
            text.append(cmd).append(" ");
        }
        System.out.println(text.toString());
    }

    private static void print(Object result) {
        System.out.println(
                result instanceof byte[]
                        ? new String((byte[]) result)
                        : result);
    }


}
